package com.self.liu.xp.base;

import org.apache.log4j.Logger;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;

import com.self.liu.xp.thrift.service.ExecuteService.Iface;
import com.self.liu.xp.thrift.service.ExecuteService.Processor;

/*
 * ThriftServer 基类
 */
public class ThriftServer extends Thread {

    /* log */
    private static Logger logger = Logger.getLogger(ThriftServer.class);

    /* 服务使用的端口号 */
    protected int port;

    /* Thrift Server */
    private TServer server;

    /*
     * 开启Server服务
     */
    public void open() {
        super.start();
    }

    /*
     * 关闭Server服务
     */
    public void close() {
        if (server != null) {
            server.stop();
            logger.info("Port:" + port + " Service is closed.");
        }
    }

    /*
     * 开启服务
     */
    @Override
    public void run() {
        super.run();
        server = creatServer();
        if (server != null) {
            logger.info("Port:" + port + " Service is open.");
            server.serve();
        } else {
            logger.error("No Found Server, please create it.");
        }
    }

    /* 
     * 创建TServer 
     * 
     */
    private TServer creatServer() {
        TServerTransport serverTransport;
        try {
            serverTransport = new TServerSocket(port);
            TProcessor tprocessor = new Processor<Iface>(new Executor());
            Args ttpsArgs = new Args(serverTransport);
            ttpsArgs.processor(tprocessor);
            ttpsArgs.protocolFactory(new TCompactProtocol.Factory());
            TServer server = new TThreadPoolServer(ttpsArgs);
            logger.info(this.getName() + "-ThriftServer is created on port " + port + ".");
            return server;
        } catch (TTransportException e) {
            logger.error("ThriftServer create failed. Case:" + e.getMessage());
        }
        return null;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

}
